/*
 * Copyright (c)  2020,  DataPipeline
 * All rights reserved.
 *
 * Id:TailBean.java   2020-07-15 00:19 wanglijun
 */
package cn.datacare.orm.damoin;

import cn.datacare.orm.exception.OrmCoreException;
import cn.datacare.orm.exception.OrmErrorCode;
import cn.datacare.orm.mapping.lazy.LazyEntity;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * Title: TailBean
 * </p>
 * <p>
 * Description:  使用此可以用于模板引擎，如果对于序列化，所有值都在getTails方法里,TailBean兼容了对LazyEnity的调用
 * </p>
 * <p>
 * Copyright: Copyright (c) 2020
 * </p>
 * <p>
 * Company/Department: DataPipeline
 * </p>
 *
 * @author wanglijun
 * @version 1.0
 * @since 2020-07-15 00:19
 */
public class TailBean implements Tail {
    /***
     * 预计常用字段，为5个左右
     */
    protected Map<String, Object> extMap = new HashMap<>(5);

    /***
     * 是否懒加载
     */
    boolean hasLazy = false;

    /***
     * 获取数据
     * @param key KEY
     * @return Object Value
     */
    @Override
    public Object get(String key) {
        if (!hasLazy) {
            return extMap.get(key);
        }
        Object o = extMap.get(key);
        //不等于LazyEntity ,则直接返回
        if (!(o instanceof LazyEntity)) {
            return o;
        }
        LazyEntity lazyEntity = (LazyEntity) o;
        try {
            Object real = lazyEntity.get();
            extMap.put(key, real);
            return real;
        } catch (RuntimeException e) {
            throw new OrmCoreException(OrmErrorCode.ORM_LAZY_ERROR, e, e.getMessage(), key);
        }

    }

    /***
     * 设置
     * @param key KEY
     * @param value VALUE
     */
    @Override
    public void set(String key, Object value) {
        if (value instanceof LazyEntity) {
            this.hasLazy = Boolean.TRUE;
        }
        this.extMap.put(key, value);
    }

    /**
     * 获取数据
     * @return Map<String, Object>
     */
    public Map<String, Object> getTails() {
        Map<String, Object> newExtMap = new HashMap<>();
        if (!hasLazy) {
            return extMap;
        }
        for (Map.Entry<String, Object> entry : extMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof LazyEntity) {
                try {
                    LazyEntity lazyEntity = (LazyEntity) value;
                    Object real = lazyEntity.get();
                    newExtMap.put(key, real);
                } catch (RuntimeException ex) {
                    throw new OrmCoreException(OrmErrorCode.ORM_LAZY_ERROR, ex, key, ex.getMessage());
                }

            } else {
                newExtMap.put(key, value);
            }
        }
        extMap = newExtMap;
        hasLazy = false;
        return newExtMap;
    }
}
